package ru.fivestarter.multileveledcache.strategy;


import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;


public class LRUCounter implements Counter {
    private SortedMap<java.lang.Long, String> map=new TreeMap<java.lang.Long, String>();
    private int maxcount;
    private int count;
    public LRUCounter(int c){
        this.maxcount=c;
        this.count=c;
    }

    @Override
    public String add(Long time, String key) {
        if(count>0){
            map.put(time, key);
            count--;
            return null;
        }
        else{
            String result;
            result=map.get(map.firstKey());
            map.remove(map.firstKey());
            return result;
        }
    }

    @Override
    public void remove(String key) {
        Iterator iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            Long k=(Long)iterator.next();
            if(map.get(k).equals(key)){
                map.remove(k);
                count++;
                return;
            }
            
        }
    }

    @Override
    public void refresh(Long time, String key) {
        Iterator iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            Long k=(Long)iterator.next();
            if(map.get(k).equals(key)){
                map.remove(k);
                map.put(time, key);
                return;
            }
            
        }
    }

    @Override
    public void clear() {
        map.clear();
        count=maxcount;
    }
}
